from django.views import View

from Venue.models import Venue, GoodsType
from sportsground.utils import Req
from sportsground.utils.Res import Res
from sportsground.utils.views import LoginRequired


class GoodsTypeView(View):
    """ 商品类型信息 """

    def get(self, request):
        """ 查询 """
        venue = Venue.objects.get(id=1)
        goodTypes = GoodsType.objects.filter(venue=venue).all()
        lists = []
        for goodType in goodTypes:
            lists.append(goodType.Info())
        return Res.Json(Res.OK, result=lists)

    @LoginRequired.Venue
    @Req.getJson
    def post(self, request):
        """ 添加 """
        desc = request.json_dict.get("desc")

        venue = request.user.venue
        goodType = GoodsType.create(venue=venue, desc=desc)
        return Res.Json(Res.OK, result=goodType.Info())

    @LoginRequired.Venue
    @Req.getJson
    def put(self, request):
        """ 修改 """
        id = request.json_dict.get("id")
        desc = request.json_dict.get("desc")

        venue = request.user.venue

        goodType = GoodsType.objects.filter(venue=venue, id=id).first()
        if not goodType:
            return Res.Json(Res.ParamErr)

        goodType.desc = desc
        goodType.save()
        return Res.Json(Res.OK, result=goodType.Info())

    @LoginRequired.Venue
    @Req.getJson
    def delete(self, request):
        """ 添加 """
        id = request.json_dict.get("id")

        venue = request.user.venue

        goodType = GoodsType.objects.filter(venue=venue, id=id).first()
        if not goodType:
            return Res.Json(Res.ParamErr)

        goodType.delete()
        return Res.Json(Res.OK)
